package com.mentalhealthplatform.teacherV2.controller;

import com.mentalhealthplatform.appModels.Article;
import com.mentalhealthplatform.teacherV2.service.ArticleServiceV2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/api/articles")
public class ArticleControllerV2 {

    @Autowired
    private ArticleServiceV2 articleService;

    // 获取所有文章的接口
    @GetMapping
    public ResponseEntity<List<Article>> getAllArticles() {
        try {
            List<Article> articles = articleService.getAllArticles();
            return ResponseEntity.ok(articles);
        } catch (Exception e) {
            e.printStackTrace(); // 记录详细错误
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Collections.singletonList(new Article()));
        }
    }

    // 获取指定文章的接口
    @GetMapping("/{id}")
    public ResponseEntity<Article> getArticleById(@PathVariable String id) {
        try {
            Long articleId = Long.parseLong(id);
            Article article = articleService.getArticleById(articleId);
            if (article == null) {
                return ResponseEntity.notFound().build();
            }
            return ResponseEntity.ok(article);
        } catch (NumberFormatException e) {
            return ResponseEntity.badRequest().body(null);
        } catch (Exception e) {
            e.printStackTrace(); // 记录详细错误
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(null);
        }
    }

    // 搜索文章的接口
    /*@GetMapping("/search")
    public ResponseEntity<List<Article>> searchArticles(@RequestParam String query) {
        try {
            List<Article> articles = articleService.searchArticles(query);
            return ResponseEntity.ok(articles);
        } catch (Exception e) {
            e.printStackTrace(); // 记录详细错误
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Collections.emptyList());
        }
    }*/
}